package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import protocal.DataPackage;
import protocal.DataPackage.MessageType;

public class IMThread extends Thread{

	private Socket socket;
	static Map<String, Socket> onlineList = new HashMap<String, Socket>();
	public IMThread() {}
	public IMThread(Socket socket){
		this.socket = socket;
	}
	
	@Override
	public void run() {
		
		/*
		 * 操作online list
		 */
		try {
			InputStream iStream = socket.getInputStream();
			OutputStream oStream = socket.getOutputStream();
			try {
				while (true) {
					ObjectOutputStream outputStream = new ObjectOutputStream(oStream);
					ObjectInputStream oInputStream = new ObjectInputStream(iStream);
					DataPackage dPackage = (DataPackage)oInputStream.readObject();
					System.out.println(dPackage.toString());
					if(dPackage.getMessageType()==MessageType.LOGIN){
						onlineList.put(dPackage.getFromeName(), socket);
						hintAll(onlineList,dPackage);
					}else if(dPackage.getMessageType()==MessageType.LOGOUT){
						if(onlineList.containsKey(dPackage.getFromeName())){
							onlineList.remove(dPackage.getFromeName());
							hintAll(onlineList,dPackage);
						}
					}else{
						forwardMessage(onlineList,dPackage);
					}
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			iStream.close();
			oStream.close();
//			oInputStream.close();
//			outputStream.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * update onlinelist and send to client
	 * @param onlineList
	 * @param dPackage
	 * @throws IOException
	 */
	public void hintAll(Map<String, Socket> onlineList,DataPackage dPackage) throws IOException{
		for(Socket socket:onlineList.values()){
			System.out.println("hinting....");
			OutputStream oStream = socket.getOutputStream();
			oStream.write((dPackage.getFromeName()+"\n").getBytes());
		}
	}

	/**
	 * forword message to client
	 * @param onlineList
	 * @param dPackage
	 * @throws IOException
	 */
	public void forwardMessage(Map<String, Socket> onlineList, DataPackage dPackage) throws IOException{
		System.out.println("forward....");
		if(dPackage.getToName().contains("\\\\")){
			String[] toName = dPackage.getToName().split("\\\\");
			for(String name:toName){
				OutputStream oStream2 = onlineList.get(name).getOutputStream();
				ObjectOutputStream ooStream = new ObjectOutputStream(oStream2);
				ooStream.writeObject(dPackage);
			}
		}else{
			OutputStream oStream2 = onlineList.get(dPackage.getToName()).getOutputStream();
			ObjectOutputStream ooStream = new ObjectOutputStream(oStream2);
			ooStream.writeObject(dPackage);
		}
	}
	
}
